package com.atguigu.mySmartCampus.controller;

import com.atguigu.mySmartCampus.Service.AdminService;
import com.atguigu.mySmartCampus.entity.Admin;
import com.atguigu.mySmartCampus.util.MD5;
import com.atguigu.mySmartCampus.util.Result;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@Api
@RequestMapping("/sms/adminController")
public class AdminController {
    @Autowired
    private AdminService adminService;

    @ApiOperation("管理员列表页")
    @GetMapping("/getAllAdmin/{pageNum}/{pageSize}")
    public Result getAllAdmin(
            @PathVariable Integer pageNum,
            @PathVariable Integer pageSize,
            String adminName) {
        System.out.println("AdminController.getAllAdmin"
        +"\n--> pageNum="+pageNum
        +"\n--> pageSize="+pageSize
        +"\n--> adminName="+adminName
        );
        Page<Admin> adminPage = new Page<>(pageNum, pageSize);
        IPage<Admin> adminIPage = adminService.selectAdminByOperator(adminPage, adminName);
        Result res = new Result();
        Result<IPage<Admin>> ok = res.ok(adminIPage);
        return ok;
    }

    @ApiOperation("添加或修改管理员")
    @PostMapping("/saveOrUpdateAdmin")
    public Result saveOrUpdateAdmin(@RequestBody Admin admin) {
        Integer id = admin.getId();
        if (id == null || id == 0) {
            admin.setPassword(MD5.encrypt(admin.getPassword()));
        }
        boolean update = adminService.saveOrUpdate(admin);
        if (update) {
            return Result.ok();
        }
        return Result.fail();
    }

    @DeleteMapping("/deleteAdmin")
    public Result deleteAdmin(@ApiParam("n个管理员id列表") @RequestBody List<Integer> deleteAdminIds) {

        boolean res = adminService.removeByIds(deleteAdminIds);
        if (res) {
            return Result.ok();
        }
        return Result.fail();
    }
}
